<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/5/31
 * Time: 13:23
 */

namespace app\admin\controller\warehouse;

use app\admin\BaseController;
use app\admin\model\Product;
use app\admin\model\WarehouseGeneral;
use app\admin\model\WarehouseGeneralSku;
use app\admin\model\WarehouseListDetail;
use app\lib\exception\FailedException;
use app\lib\exception\NoJurisdiction;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\Validate\ActionMustPositiveValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\WarehouseListValidate;
use think\Db;
use think\Request;

class WarehouseList extends BaseController{
    /**
     * 入库单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_receipt(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 补货单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_replenishment(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 出货单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_outbound(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 调批单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_adjustment(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 退货单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_return(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 其它单据列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list_other(Request $request){
        return $this->approval_list($request);
    }

    /**
     * 审批单
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function approval_list(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        if($post['page']==0){
            $post['page'] = 1;
            $post['page_number'] = 999999;
        }
        $where=[];
        if(isset($post['type'])){
            $where[] = ['a.type','eq',$post['type']];
        }
        if(isset($post['status'])){
            if($post['status']!='all'){
                $where[] = ['a.status','eq',$post['status']];
            }
        }
        if(!empty($post['product_name'])){
            $product_id = (new \app\admin\model\Product())->where([
                [
                    'product_name','like','%'.$post['product_name'].'%'
                ]
            ])->column('id');

            $list_id = (new \app\admin\model\WarehouseListDetail())->where([
                [
                    'product_id','in',$product_id
                ]
            ])->column('list_id');

            $where[] = [
                'a.id','in',$list_id
            ];
        }


        $where = addWhere($post,['order_number'=>""],$where,2,"a.");// 各种单号
        //$where = addWhere($post,['product_name'=>""],$where,2,"b.");//商品名称
        $where = addWhere($post,['name'=>""],$where,2,"c.");//商家名称
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] =strtotime($post['min_time']);
            $post['max_time'] =strtotime($post['max_time']);
            $where[] = ['a.create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] =strtotime($post['min_time']);
            $where[] = ['a.create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] =strtotime($post['max_time']);
            $where[] = ['a.create_time','elt',$post['max_time']];
        }
        $admin = $this->admin;
        if($admin['account_type']==2){//如果账号类型是2 就要查商家下的商品
            if(in_array($post['type'],[2,3,5])){//交易大厅商家下的补货单，出库单 退货单
                $where[] =['a.uid','eq',$admin['uid']];//账号绑定的商家id
            }
            if($post['type']==4){ //商家下的调批单 需要传从哪个目标仓库 调到总仓的 需要warehouse_id
                if(!isset($post['warehouse_id'])){
                    throw new ParameterException(['msg'=>'缺少目标仓库id']);
                }
                $where[] =['a.warehouse_id','eq',$post['warehouse_id']];
//                $product = (new Product())->where([['uid','eq',$admin['uid']]])->column("id");
//                $list_id = (new WarehouseListDetail())->where([['product_id','in',$product]])->column("list_id");
//                $list_id = array_unique($list_id);
//                $where[] =['a.id','in',$list_id];
            }
        }else{//账号类型是1 是平台账号 就查平台下面的 所有单据
            $where[] =['a.id','gt',0];
        }
        $field = "a.*,c.name,b.warehouse_name,b.type";
        $dataList = (new \app\admin\model\WarehouseList())
            ->alias("a")
            ->join("om_warehouse b","b.id = a.warehouse_id","right")
            ->join("om_shop c","c.id = a.uid","left")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $count   = $dataList['total'];
        $dataList = $dataList['data'];
        foreach ($dataList as $key=>$value){
            $dataList[$key]['product_sku_number']=(new WarehouseListDetail())->getCount([['list_id','eq',$value['id']]]);
        }
        $returnList = [
//            'product' =>$product,
//            'where' =>$where,
            'count'=>$count,
            'dataList'=>$dataList
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 添加操作单
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     * @throws NoJurisdiction
     */
    public function approval_add(Request $request){
        (new WarehouseListValidate())->goCheck();
        $post = $request->post();
        if (!array_key_exists('productList', $post)) {
            throw (new FailedException(['msg'=>'缺少商品数组']));
        }
        $admin = $this->admin;
        if($admin['account_type']==2){
            if($post['uid']!=$admin['uid']){ throw new NoJurisdiction();}
        }

        $new = [
            'type'=>$post['type'],
            'uid'=>$post['uid'],
            'from_warehouse_id'=>isset($post['from_warehouse_id'])? $post['from_warehouse_id'] : 0,
            'warehouse_id'=>$post['warehouse_id'],
            'total_stock'=>0,
            'order_number'=>(new \app\admin\model\WarehouseList())->createOrderNumber("WL"),
            'edit_status' =>isset($post['edit_status'])?$post['edit_status']:1,
            'remark' =>isset($post['remark'])?$post['remark']:"",
            'linkman' =>isset($post['linkman'])?$post['linkman']:"",//联系人
            'contact_number' =>isset($post['contact_number'])?$post['contact_number']:"",//联系电话
            'address' =>isset($post['address'])?$post['address']:"",//联系地址
            'province' =>isset($post['province'])?$post['province']:"",//省
            'city' =>isset($post['city'])?$post['city']:"",//市
            'area' =>isset($post['area'])?$post['area']:"",//区
        ];

        if($post['type']==1){//1表示入库单 默认是审核通过
           $new['status'] =1;
        }
        if($post['type']==4){//4表示调批单  默认不能修改
            $new['edit_status']=2;
        }
        if($post['type']==6){ //6表示其他单据 直接转库存
            $new['status'] =2;
            $new['edit_status']=2;
        }
        foreach($post['productList'] as $key=>$value){
            $new['total_stock']+=$value['plan_stock']?$value['plan_stock']:0;
        }

        Db::startTrans();
        $list_id = (new \app\admin\model\WarehouseList())->dataUpdate($new);
        if(!$list_id){
            Db::rollback();
            throw (new FailedException(['msg'=>'添加总订单失败']));
        }
        $newList = [];
        foreach ($post['productList'] as $key=>$value){
            $newList[] =[
                'uid'    =>$post['uid'],
                'sku'    =>$value['sku'],
                'list_id'=>$list_id,
                'product_id'=>$value['product_id'],
                'plan_stock'=>isset($value['plan_stock'])?$value['plan_stock']:0,//计划入库
                'actual_stock'=>isset($value['plan_stock'])?$value['plan_stock']:0,//实际入库
                'product_time'=>isset($value['product_time'])?strtotime($value['product_time']):time(),//生产时间
                'warning_time'=>isset($value['warning_time'])?strtotime($value['warning_time']):time(),//预警时间
                'warning_stock'=>isset($value['warning_stock'])?$value['warning_stock']:0,//预警库存
                'remark'=>isset($value['remark'])?$value['remark']:"",//批次的备注
                'batch_number'=>isset($value['batch_number'])?$value['batch_number']:"",//批次号
                'create_time'  =>time(),
                'update_time'  =>time(),
            ];
        }
        if(count($newList)==0){
            if(!$list_id){
                Db::rollback();
                throw (new FailedException(['msg'=>'请先添加商品']));
            }
        }
        $res = (new WarehouseListDetail())->saveAll($newList);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'生成订单失败']));
        }
        if($post['type']==6){
            //如果是6直接走 确认完成直接入库成功
            // 虚拟仓库+库存
            $list =  (new \app\admin\model\WarehouseList())->findOne([['id','eq',$list_id]]);
            $detail  = (new WarehouseListDetail()) ->selectList([['list_id','eq',$list_id]]);
            $detail  =$detail->toArray();
            $res = warehouseChangeStock($list['warehouse_id'],1,$detail);
            if($res['code']!=1){
                Db::rollback();
                throw new FailedException(['msg'=>$res['msg']]);
            }
            //总仓库减库存
            $res=warehouseChangeStock(1,2,$detail);
            if($res['code']!=1){
                Db::rollback();
                throw new FailedException(['msg'=>$res['msg']]);
            }
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 查询审批单详情
     * ID  审批单的id
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function approval_detail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $list = (new \app\admin\model\WarehouseList())->findOne([['id','eq',$post['id']]]);
        if(!$list){
            throw new NotFoundException(['msg'=>'审批单不存在']);
        }
        $where[] =['a.list_id','eq',$post['id']];
        $field = "a.*,b.cover_img,b.product_name,b.international_code,b.sku_remark";
        $list['detail'] = (new WarehouseListDetail())
            ->alias("a")
            ->join("om_product b","a.product_id = b.id","left")
            ->where($where)
            ->field($field)
            ->select();
        $product_price_model = new \app\admin\model\ProductPrice();
        $warehouse_general_model = new \app\admin\model\WarehouseGeneral();
        foreach ($list['detail'] as &$value){
            $value['price'] = $product_price_model->where([['product_id','eq',$value['product_id']],['type','eq',1]])->value('price');
            $value['stock'] = $warehouse_general_model->where([['product_id','eq',$value['product_id']]])->value('stock');
            $value['stock'] = $value['stock'] == null ? 0 : $value['stock'];
            $value['cover_img'] = imgUrlToAbsolute($value['cover_img']);
            $value['product_time'] = date("Y-m-d",$value['product_time']);
            $value['warning_time'] = date("Y-m-d",$value['warning_time']);
        }
        return writeJson(200,['list'=>$list]);
    }

    /**
     * 编辑操作单
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \app\lib\exception\ParameterException
     */
    public function approval_edit(Request $request){
        (new WarehouseListValidate())->goCheck();
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        if (!array_key_exists('productList', $post)) {
            throw (new FailedException(['msg'=>'缺少商品数组']));
        }
        $detail = (new \app\admin\model\WarehouseList())->findOne([['id','eq',$post['id']]]);
        if(!$detail||$detail['edit_status']!=1){
            throw (new FailedException(['msg'=>'表单不可编辑']));
        }
        $new = [
            'id'            =>$post['id'],
            'type'          =>$post['type'],
            'uid'           =>$post['uid'],
            'warehouse_id'  =>$post['warehouse_id'],
            'total_stock'   =>0,
            'edit_status'   =>$post['edit_status']
        ];
        foreach($post['productList'] as $key=>$value){
            if($post['type']==1){
                $new['total_stock']+=isset($value['plan_stock'])?$value['plan_stock']:0;
            }else{
                $new['total_stock']+=isset($value['actual_stock'])?$value['actual_stock']:0;
            }
        }
        Db::startTrans();
        $list_id = (new \app\admin\model\WarehouseList())->dataUpdate($new);
        if(!$list_id){
            Db::rollback();
            throw (new FailedException(['msg'=>'添加总订单失败']));
        }
        //先删除之前的订单 在生成新的
        $result  =  (new \app\admin\model\WarehouseListDetail())->fieldUpdate('delete_time',time(),'',[['list_id','eq',$post['id']]]);
        if(!$result){
            Db::rollback();
            throw (new FailedException(['msg'=>'删除子订单失败']));
        }
        $newList = [];
        foreach ($post['productList'] as $key=>$value){
            $newList[] =[
                'uid'    =>$post['uid'],
                'list_id'=>$list_id,
                'product_id'=>$value['product_id'],
                'sku'=>$value['sku'],
                'plan_stock'=>isset($value['plan_stock'])?$value['plan_stock']:0,//计划入库
                'actual_stock'=>isset($value['actual_stock'])&&$post['type']!=1?$value['actual_stock']:$value['plan_stock'],//实际入库
                'product_time'=>isset($value['product_time'])?strtotime($value['product_time']):time(),//生产时间
                'warning_time'=>isset($value['warning_time'])?strtotime($value['warning_time']):time(),//预警时间
                'warning_stock'=>isset($value['warning_stock'])?$value['warning_stock']:"",//预警库存
                'remark'=>isset($value['remark'])?$value['remark']:"",//批次的备注
                'batch_number'=>isset($value['batch_number'])?$value['batch_number']:"",//批次号
                'create_time'  =>time(),
                'update_time'  =>time(),
            ];
        }
        if(count($newList)==0){
            if(!$list_id){
                Db::rollback();
                throw (new FailedException(['msg'=>'请先添加商品']));
            }
        }
        $res = (new WarehouseListDetail())->saveAll($newList);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'生成订单失败']));
        }
        Db::commit();
        return writeJson(200,[],'修改订单成功');
    }

    /**
     * 编辑操作单
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function approval_check(Request $request){
        (new ActionMustPositiveValidate())->goCheck();
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $list = (new \app\admin\model\WarehouseList())->findOne([['id','eq',$post['id']]]);
        if(!$list){
            throw new NotFoundException(['msg'=>'操作单不存在']);
        }

        if($post['action_type']=="over"){ //表示 入库单 完成入库操作
            if($list['edit_status']!=1){
                throw new FailedException(['msg'=>'操作单不能完成入库']);
            }
            $new = [
                'id'=>$post['id'],
                'edit_status'=>2,//1 是通过 -1是不通过
              ];
              $res = (new \app\admin\model\WarehouseList())->dataUpdate($new);
              if(!$res){
                  throw new FailedException(['msg'=>'操作失败']);
            }

            return writeJson(200);
        }
        if($post['action_type']=="check"){ //标识审核状态
            if($list['status']!=0){
                throw new FailedException(['msg'=>'操作单不能审核']);
            }
            $new = [
                'id'=>$post['id'],
                'status'=>$post['check_status'],//1 是通过 -1是不通过
                'check_time'=>time(),
            ];
            if($list['type']>2){//1和2是入库单和补货单不能改 编辑状态
                $new['edit_status'] = 2;
            }

            $res = (new \app\admin\model\WarehouseList())->dataUpdate($new);
            if(!$res){
                throw new FailedException(['msg'=>'操作失败']);
            }
            return writeJson(200);
        }
        if($post['action_type']=="quxiao"){ //标识审核状态
            $admin = $this->admin;
            if($admin['account_type']==2){//如果账号类型是2 就要查商家下的商品
                if($admin['uid']!=$list['uid']){
                    throw new FailedException(['msg'=>'订单不能取消']);
                }
            }
            if($list['status']!=0){
                throw new FailedException(['msg'=>'操作单不能取消']);
            }
            $new = [
                'id'=>$post['id'],
                'status'=>-2,//状态-2是取消状态
                'edit_status'=>2, //取消之后不可编辑
                'check_time'=>time(),
            ];
            $res = (new \app\admin\model\WarehouseList())->dataUpdate($new);
            if(!$res){
                throw new FailedException(['msg'=>'操作失败']);
            }
            return writeJson(200);
        }
        if($post['action_type']=="cancel"){ //确认完成这对应到添加各个仓库的订单
            $detail =  (new WarehouseListDetail())->selectList([['list_id','eq',$post['id']]]);
            $detail =  $detail->toArray();
            Db::startTrans();
            if($list['status']!=1){
                throw new FailedException(['msg'=>'操作单不能确认完成']);
            }
            $new = [
                'id'=>$post['id'],
                'status'=>2,//确认完成
                'edit_status'=>2//确认完成以后不能修改
            ];
            $res = (new \app\admin\model\WarehouseList())->dataUpdate($new);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg'=>'操作失败']);
            }
            //要查看审批单的类型 type 1是入库单 2是补货单 3是出库单 4是调批单 5退货单 6是其他单据
            if($list['type']==1&&$post['check_status']>=1){ //入库确认完成
                $res=warehouseChangeStock($list["warehouse_id"],1,$detail);
                if($res['code']!=1){
                    Db::rollback();
                    throw new FailedException(['msg'=>$res['msg']]);
                }
            }
            if($list['type']==2&&$post['check_status']>=1){ //补货单确认完成
                $res=warehouseChangeStock($list["warehouse_id"],1,$detail);
                if($res['code']!=1){
                    Db::rollback();
                    throw new FailedException(['msg'=>$res['msg']]);
                }
            }
            if($list['type']==3&&$post['check_status']>=1){ //出库单
                //出库单为线上商家自己的虚拟仓库 品牌店是自己的仓库  贸易商是中装仓 对应下面的库存
                $res=warehouseChangeStock($list['warehouse_id'],2,$detail);
                if($res['code']!=1){
                    Db::rollback();
                    throw new FailedException(['msg'=>$res['msg']]);
                }
            }
            if($list['type']==4&&$post['check_status']>=1){
                //调批单[按批次及数量调取]
                //从来源仓库向目标仓库调批数据
                $warehouseGeneralSkuService = (new \app\admin\model\WarehouseGeneralSku());
                $warehouseGeneralService = (new \app\admin\model\WarehouseGeneral());

                //-----------------------------------------------------------------------------------------
                // 阶段 1 >>>>>>
                // 1.对比要调批的批次与之前批次的关系，将原始库存批次，存入待修改中
                // 2.对比后，将要调批的数据，加入同种商品数组中，以商品的ID为键值，只保留一条数据，数量累加
                // 3.库存不足的，提示失败并更新为可重新编辑状态
                // 4.向目标仓库，目标商品创建新批次
                //------------------------------------------------------------------------------------------
                //存储当前被操作的批次ID
                $general_sku_id_arr = [];
                foreach ($detail as $k=>$v){ array_push($general_sku_id_arr,$v["general_sku_id"]); }
                //查询原始库存对应批次信息
                $generalSkuWhere[] = ["id","in",$general_sku_id_arr];
                $modelList = $warehouseGeneralSkuService
                    ->field("id,uid,product_id,sku,stock,warehouse_id,warn_stock,warn_time,product_time,list_detail_id")
                    ->where($generalSkuWhere)->order("product_id")->select()->toArray();

                //原始库存批次更新数组
                $needUpdateOldGeneralSkuList = [];

                //调批某商品的总数  字段:product_id-stock-uid
                $productAllNum = [];

                //新仓库内批次库存修改
                $needUpdateNewGeneralSkuList = [];

                foreach ($detail as $k=>$v){
                    //处理批次，在容器B中查询，需要做什么处理
                    foreach ($modelList as $k1=>$v1){
                        //* v1为原始库存批次  v为当前调批批次
                        //找到需要操作的批次
                        if ($v1["id"] == $v["general_sku_id"]){
                            $nowNumber = $v1["stock"] - $v["plan_stock"];
                            //库存小于0 抛出操作失败
                            if($nowNumber < 0){
                                //抛出库存不足失败并进行记录
                                Db::rollback();
                                //查询商品信息
                                $productICode = (new Product())->field("international_code")
                                    ->where("product_id","eq",$v["id"])->findOne();
                                //更新总单据状态,并标记失败
                                $warehouseListNew = [
                                    'id'=>$post['id'],
                                    'status'=>0,//变为待审核状态
                                    'edit_status'=>1//变为可编辑状态
                                ];
                                (new \app\admin\model\WarehouseList())->dataUpdate($warehouseListNew);
                                throw new FailedException(['msg'=>'操作失败,国编码为[' . $productICode  . ']商品的[' . $v["general_sku_id"] . ']批次剩余数量不足']);
                            }
                            //若库存剩余为0  则标记删除
                            if($nowNumber == 0){
                                $v1["delete_time"] = time();
                            }
                            //更新原始批次库存
                            $v1["stock"] = $nowNumber;

                            //将需要更改的原始库存push至数组
                            array_push($needUpdateOldGeneralSkuList,$v1);

                            //处理同批次商品总数
                            $isExist = false;
                            foreach ($productAllNum as $k2=>$v2){
                                if($v2["product_id"] == $v["product_id"]){
                                    //同商品数量递加 并进行标记
                                    $isExist = true;
                                    $productAllNum[$k2]["stock"] = $v2["stock"] + $v["plan_stock"];
                                    break;
                                }
                            }
                            //不存在则新增
                            if(!$isExist){
                                $newArray = [];
                                $newArray["product_id"] = $v["product_id"];
                                $newArray["stock"] = $v["plan_stock"];
                                $newArray["uid"] = $v["uid"];
                                array_push($productAllNum,$newArray);
                            }

                            //修改仓库信息，将其添加入新仓库批次更新数组中
                            $newGeneralModel["uid"] = $v1["uid"];
                            $newGeneralModel["product_id"] = $v1["product_id"];
                            $newGeneralModel["stock"] = $v["plan_stock"];
                            $newGeneralModel["warehouse_id"] = $list["warehouse_id"];
                            $newGeneralModel["product_time"] = $v1["product_time"];
                            $newGeneralModel["list_detail_id"] = $v["id"];
                            $newGeneralModel["warn_stock"] = $v1["warn_stock"];
                            $newGeneralModel["warn_time"] = $v1["warn_time"];
                            $newGeneralModel["create_time"] = time();
                            $newGeneralModel["update_time"] = time();
                            array_push($needUpdateNewGeneralSkuList,$newGeneralModel);
                        }
                    }
                }

                //-----------------------------------------------------------------------------------------
                // 阶段 2 >>>>>>
                // 1.查询原始库存更新情况，并对原始库存进行修改更新
                // 2.原始库存不足的，提示失败并更新为可重新编辑状态
                //------------------------------------------------------------------------------------------
                $product_id_arr = [];    //查询原始库存
                foreach ($detail as $k=>$v){ array_push($product_id_arr,$v["product_id"]); }

                $oldWarehouseGeneralWhere[] = ["warehouse_id","eq",$list["from_warehouse_id"]];
                $oldWarehouseGeneralWhere[] = ["product_id","in",$product_id_arr];
                $modelList2 = $warehouseGeneralService
                    ->field("id,uid,product_id,stock,warehouse_batches,status,update_time,admin_id,warehouse_id")
                    ->where($oldWarehouseGeneralWhere)->order("product_id")->select()->toArray();

                //原始仓库库存更新数组
                $needUpdateOldWarehouseList = [];

                foreach ($productAllNum as $k=>$v){
                    foreach ($modelList2 as $k1=>$v1){
                        if($v1["product_id"] == $v["product_id"]){
                            //商品一致，则进行对比
                            $nowNumber = $v1["stock"] - $v["stock"];
                            //库存小于0 抛出操作失败
                            if($nowNumber < 0){
                                //抛出库存不足失败并进行记录
                                Db::rollback();
                                //查询商品信息
                                $productICode = (new Product())->field("international_code")
                                    ->where("product_id","eq",$v["id"])->findOne();
                                //更新总单据状态,并标记失败
                                $warehouseListNew = [
                                    'id'=>$post['id'],
                                    'status'=>0,//变为待审核状态
                                    'edit_status'=>1//变为可编辑状态
                                ];
                                (new \app\admin\model\WarehouseList())->dataUpdate($warehouseListNew);
                                throw new FailedException(['msg'=>'操作失败,国编码为[' . $productICode  . ']商品的库存总量剩余数量不足']);
                            }

                            //更新原始库库存
                            $v1["stock"] = $nowNumber;
                            $v1["update_time"] = time();
                            $v1["admin_id"] = $post["admin_id"];

                            //将需要更改的原始库存push至数组
                            array_push($needUpdateOldWarehouseList,$v1);
                        }
                    }
                }

                //-----------------------------------------------------------------------------------------
                // 阶段 3 >>>>>>
                // 1.查询目标仓库商品情况，若有商品则新增数据，无商品则创建数据
                //------------------------------------------------------------------------------------------
                $newWarehouseGeneralWhere[] = ["product_id","in",$product_id_arr];
                $newWarehouseGeneralWhere[] = ["warehouse_id","in",$list["warehouse_id"]];
                $modelList3 = $warehouseGeneralService
                    ->field("id,uid,product_id,stock,warehouse_batches,status,update_time,admin_id,warehouse_id")
                    ->where($newWarehouseGeneralWhere)->order("product_id")->select()->toArray();

                //新仓库的修改情况
                $needUpdateNewWarehouseList = [];

                //判断新仓库是否有商品库存
                foreach ($productAllNum as $k=>$v){
                    $isExist = false;
                    foreach ($modelList3 as $k1=>$v1){
                        if($v["product_id"] == $v1["product_id"]){
                            $isExist = true;
                            $v1["stock"] = $v["stock"] + $v1["stock"];
                            $v1["warehouse_batches"] = $v1["warehouse_batches"] + 1;
                            $v1["update_time"] = time();
                            $v1["admin_id"] = $post["admin_id"];
                            array_push($needUpdateNewWarehouseList,$v1);
                        }
                    }
                    if(!$isExist){
                        //新建库存加入至仓库修改中
                        $newModel = array(
                            "uid"=>$v["uid"],
                            "product_id"=>$v["product_id"],
                            "stock"=>$v["stock"],
                            "warehouse_batches"=>1,
                            "status"=> 1,
                            "create_time"=>time(),
                            "update_time"=>time(),
                            "warehouse_id"=>$list["warehouse_id"],
                            "admin_id"=>$this->admin["id"],
                        );
                        array_push($needUpdateNewWarehouseList,$newModel);
                    }
                }

                //更新老库存
                if(Count($needUpdateOldWarehouseList) > 0){
                    $res = $warehouseGeneralService->fieldUpdateAll($needUpdateOldWarehouseList);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException(['msg'=>"修改老库存失败"]);
                    }
                }
                //更新老库存批次
                if(Count($needUpdateOldGeneralSkuList) > 0){
                    $res = $warehouseGeneralSkuService->fieldUpdateAll($needUpdateOldGeneralSkuList);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException(['msg'=>"修改老库存失败"]);
                    }
                }
                //更新新库存
                if(Count($needUpdateNewWarehouseList) > 0){
                    $res = $warehouseGeneralService->fieldUpdateAll($needUpdateNewWarehouseList);
                    if(!$res) {
                        Db::rollback();
                        throw new FailedException(['msg' => "修改新库存失败"]);
                    }
                }
                //更新新库存批次
                if(Count($needUpdateNewGeneralSkuList) > 0){
                    $res = $warehouseGeneralSkuService->fieldUpdateAll($needUpdateNewGeneralSkuList);
                    if(!$res) {
                        Db::rollback();
                        throw new FailedException(['msg' => "修改新库存失败"]);
                    }
                }
            }
            if($list['type']==5&&$post['check_status']>=1){
                //退货流程
                //获取退货单商品退货数量
                //按照退货单上商品数量，依照预警日期依次退货(生产日期靠前的先退)
                //更改总库存
                $newGeneralSkuList = []; //批次待处理
                $newGeneralList = [];    //总库存待处理
                $warehouseGeneralSkuService = (new \app\admin\model\WarehouseGeneralSku());
                $warehouseGeneralService = (new \app\admin\model\WarehouseGeneral());
                foreach ($detail as $k=>$v){ //当前计划退货批次详情
                    //获取当前商品所有库存非0批次
                    $where = [];
                    $where[] = ["stock","gt",0];
                    $where[] = ["product_id","eq",$v["product_id"]];
                    $where[] = ["warehouse_id","eq",1];

                    $nowList = $warehouseGeneralSkuService
                        ->field("id,product_id,sku,stock,warehouse_id,warn_stock,warn_time,product_time,list_detail_id")
                        ->where($where)->order("warn_time asc")->select()->toArray();

                    //当前总共退货数量
                    $number = $v["plan_stock"];
                    //计算批次库存更改
                    foreach ($nowList as $k1=>$v1){
                        if(($number - $v1["stock"]) > 0){
                            $number = $number - $v1["stock"];
                            $v1["stock"] = 0;
                            $v1["update_time"] = time();
                        }else{
                            $v1["stock"] = $v1["stock"] - $number;
                            $v1["update_time"] = time();
                            $number = 0;
                        }
                        array_push($newGeneralSkuList,$v1);
                        if($number == 0){
                            break;
                        }
                    }
                    if($number > 0){
                        Db::rollback();
                        throw new FailedException(['msg'=>"修改批次失败,当前各批次库存不足"]);
                    }

                    //计算总库存更改
                    $number = $v["plan_stock"];
                    $generalWhere = [];
                    $generalWhere[] = ["product_id","eq",$v["product_id"]];
                    $generalWhere[] = ["warehouse_id","eq",1];
                    $nowGeneral = $warehouseGeneralService
                        ->field("id,uid,product_id,stock,warehouse_batches,status,admin_id,warehouse_id")
                        ->where($generalWhere)->find()->toArray();
                    $nowGeneral["stock"] = $nowGeneral["stock"] - $number;
                    if($nowGeneral["stock"] < 0){
                        Db::rollback();
                        throw new FailedException(['msg'=>"修改批次失败,总仓库库存不足"]);
                    }
                    array_push($newGeneralList,$nowGeneral);
                }
                //更新批次仓库
                $res = $warehouseGeneralSkuService->fieldUpdateAll($newGeneralSkuList);
                if(!$res){
                    Db::rollback();
                    throw new FailedException(['msg'=>"修改批次库存失败"]);
                }
                //更新总仓库
                $res = $warehouseGeneralService->fieldUpdateAll($newGeneralList);
                if(!$res){
                    Db::rollback();
                    throw new FailedException(['msg'=>"修改总仓库库存失败"]);
                }
            }
            if($list['type']==6&&$post['check_status']>=1){ //其他单据 就是往自己添加的虚拟仓库调批东西
                // 虚拟仓库+库存
                $res = warehouseChangeStock($list['warehouse_id'],1,$detail);
                if($res['code']!=1){
                    Db::rollback();
                    throw new FailedException(['msg'=>$res['msg']]);
                }
                //总仓库减库存
                $res=warehouseChangeStock(1,2,$detail);
                if($res['code']!=1){
                    Db::rollback();
                    throw new FailedException(['msg'=>$res['msg']]);
                }
            }

            Db::commit();
            return writeJson(200,[],'操作成功');
        }
    }

    /**
     * 查询批次信息
     * 必传仓库id
     * 选传国际编码  商品名称  商家名称
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     * @throws \think\exception\DbException
     */
    public function getGeneralSkuList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        if(!isset($post["warehouse_id"]) || $post["warehouse_id"] == ""){ return writeJson("500","请选择来源仓库","请选择来源仓库","500");}

        $where[] = ['om_warehouse_general_sku.warehouse_id','eq',$post['warehouse_id']]; //仓库ID
        if(isset($post["product_name"]) && $post["product_name"] != ""){ $where[] = [ 'product_name','like','%'.$post['product_name'].'%'];} //商品名称
        if(isset($post["international_code"]) && $post["international_code"] != ""){ $where[] = [ 'international_code','like','%'.$post['international_code'].'%'];} //国际编码
        if(isset($post["shop_name"]) && $post["shop_name"] != ""){ $where[] = [ 'om_shop.name','like','%'.$post['shop_name'].'%']; }  //商家名称

        /**
            select
            om_warehouse_general_sku.id,
            om_warehouse_general_sku.product_id,
            om_warehouse_general_sku.sku,
            om_warehouse_general_sku.stock,
            om_warehouse_general_sku.warn_stock,
            FROM_UNIXTIME(om_warehouse_general_sku.product_time) as product_time,
            FROM_UNIXTIME(om_warehouse_general_sku.warn_time) as warn_time,
            om_shop.name,
            product_name,
            cover_img,
            product_price_one,
            sku_remark,
            international_code,
            om_warehouse_general.stock
            from om_warehouse_general_sku
            inner join om_product on om_warehouse_general_sku.product_id = om_product.id
            inner join om_shop on om_shop.id = om_product.uid
            LEFT JOIN `om_warehouse_general` ON `om_warehouse_general`.`uid` = om_warehouse_general_sku.uid
            and `om_warehouse_general`.`warehouse_id` = om_warehouse_general_sku.warehouse_id
            AND om_warehouse_general.product_id = om_warehouse_general_sku.product_id
            and product_name like '%测试%'
            and international_code like '%123%'
            and om_shop.name like '%测试%'
            order by om_warehouse_general_sku.id
         */
        $field="om_warehouse_general_sku.id,
            om_warehouse_general_sku.product_id,om_warehouse_general_sku.sku,om_warehouse_general_sku.stock, om_warehouse_general_sku.warn_stock,FROM_UNIXTIME(om_warehouse_general_sku.product_time) as product_time,FROM_UNIXTIME(om_warehouse_general_sku.warn_time) as warn_time,om_shop.name as shop_name,product_name,cover_img,product_price_one,sku_remark,international_code,om_warehouse_general.stock as warehouse_stock";
        $dataList = (new \app\admin\model\WarehouseGeneralSku())
            ->field($field)
            ->join("om_product","om_warehouse_general_sku.product_id = om_product.id")
            ->join("om_shop","om_shop.id = om_product.uid")
            ->join("om_warehouse_general","om_warehouse_general.uid = om_warehouse_general_sku.uid and om_warehouse_general.product_id = om_warehouse_general_sku.product_id and om_warehouse_general.warehouse_id = om_warehouse_general_sku.warehouse_id","left")
            ->where($where)
            ->whereNull("om_product.delete_time")
            ->order("om_warehouse_general_sku.id desc")
            ->paginate($post['page_number'], false, [ 'page' => $post['page']])
            ->each(function ($item){
                $item['cover_img'] = imgUrlToAbsolute($item['cover_img']);
                return $item;
            });

        $dataList=$dataList->toArray();
        return writeJson(200,$dataList);
    }

    /**
     * 提交调批单
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function setTransferOrder(Request $request){
        $post = $request->post();
        if (!array_key_exists('productList', $post)) { throw (new FailedException(['msg'=>'缺少批次数组'])); }

        if(!isset($post['from_warehouse_id']) || $post['from_warehouse_id'] == ""){
            return writeJson("200","缺少来源仓库ID","缺少来源仓库ID","200");
        }
        if(!isset($post['warehouse_id']) || $post['warehouse_id'] == ""){
            return writeJson("200","缺少去向仓库ID","缺少去向仓库ID","200");
        }


        Db::startTrans();
        $new = [];
        if(!isset($post['id'])){
            //新建单据
            $new = [
                'type'=> 4,
                'uid'=> 0,
                'from_warehouse_id'=>$post['from_warehouse_id'],
                'warehouse_id'=>$post['warehouse_id'],
                'total_stock'=>0,
                'order_number'=>(new \app\admin\model\WarehouseList())->createOrderNumber("WL"),
                'edit_status' =>isset($post['edit_status'])?$post['edit_status']:2,
                'remark' =>isset($post['remark'])?$post['remark']:"",
            ];
        }else{
            $editWhere["id"] = $post['id'];
            $new = (new \app\admin\model\WarehouseList())
                ->field("id,edit_status,total_stock")->where($editWhere)->find();
            if($new == null){
                return writeJson("200","该调批单不存在","该调批单不存在","200");
            }
            $new = $new->toArray();

            if(isset($post['edit_status'])){
                $new["edit_status"] = $post['edit_status'];
            }
            //重置总入库数
            $new['total_stock'] = 0;
            //先删除之前的订单子订单 后面在生成新的
            $result = (new \app\admin\model\WarehouseListDetail())->fieldUpdate('delete_time',time(),'',[['list_id','eq',$post['id']]]);
            if(!$result){
                Db::rollback();
                throw (new FailedException(['msg'=>'删除子订单失败']));
            }
        }

        //计算总数
        foreach($post['productList'] as $key => $value){
            $new['total_stock']+= $value['plan_stock'] ? $value['plan_stock'] : 0;
        }

        $list_id = (new \app\admin\model\WarehouseList())->dataUpdate($new);
        if(!$list_id){
            Db::rollback();
            throw (new FailedException(['msg'=>'添加总订单失败']));
        }
        $newList = [];
        foreach ($post['productList'] as $key=>$value){
            $newList[] =[
                'uid'    => 0,
                'sku'    =>$value['sku'],
                'list_id'=>$list_id,
                'product_id'=>$value['product_id'],
                'plan_stock'=>$value['plan_stock'],//计划入库
                'actual_stock'=>$value['plan_stock'],//实际入库
                'product_time'=>isset($value['product_time'])?strtotime($value['product_time']):time(),//生产时间
                'warning_time'=>isset($value['warning_time'])?strtotime($value['warning_time']):time(),//预警时间
                'warning_stock'=>isset($value['warning_stock'])?$value['warning_stock']:0,//预警库存
                'general_sku_id'=>$value["id"],//调批批次ID
                'create_time'  =>time(),
                'update_time'  =>time(),
            ];
        }
        if(count($newList)==0){
            if(!$list_id){
                Db::rollback();
                throw (new FailedException(['msg'=>'请先添加批次']));
            }
        }
        $res = (new WarehouseListDetail())->saveAll($newList);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'生成失败']));
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * [商家]通过条件搜索出某商家下的有库存的多条商品
     * international_code 国际编码
     * product_name 商品名称
     * @param Request $requestf
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws ParameterException
     */
    public function searchUidHouseProduct(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        $where[] = ["warehouse_id","eq",1];
        if($admin['account_type']==2){//如果是商家账号
            $where[] = ['om_warehouse_general.uid','eq',$admin['uid']];
        }
        if(isset($post["international_code"])){
            $where[] = [ 'om_product.international_code','like','%'.$post['international_code'].'%'];
        }
        if(isset($post["product_name"])){
            $where[] = [ 'om_product.product_name','like','%'.$post['product_name'].'%'];
        }
        /**
         * select om_warehouse_general.*,om_product.sku_remark,om_product.product_name,om_product.product_price_one,om_product.cover_img from om_warehouse_general
           inner join  on
           where om_warehouse_general.uid = 213 and warehouse_id = 1
         */
        $field = "om_warehouse_general.*,om_product.sku_remark as sku,om_product.product_name,om_product.product_price_one,om_product.cover_img,om_product.international_code";
        $product = (new \app\admin\model\WarehouseGeneral())
            ->join("om_product","om_warehouse_general.product_id = om_product.id")
            ->field($field)
            ->where($where)
            ->order("om_warehouse_general.id desc")
            ->paginate($post['page_number'], false, [
                'page' => $post['page']])->each(function ($item){
                $item['cover_img'] = imgUrlToAbsolute($item['cover_img']);
                return $item;
            });
        return writeJson(200,$product);
    }

    /**
     * 查询某商品在某仓库下的仓库信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProductHouseSkuList(Request $request){
        $post = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==2){//如果是商家账号
            return writeJson(500,[],"您没有权限","500");
        }
        if(!isset($post["product_id"])){
            return writeJson(500,[],"商品ID传入有误","500");
        }

        $where["warehouse_id"] = isset($post["warehouse_id"]) ? $post["warehouse_id"] : 1;
        $where["product_id"] = $post["product_id"];

        $list = (new \app\admin\model\WarehouseGeneralSku())
            ->field("id,list_detail_id,product_id,FROM_UNIXTIME(product_time) as product_time,sku,stock,warehouse_id,warn_stock,FROM_UNIXTIME(warn_time) as warn_time")
            ->where($where)
            ->order("id desc")
            ->select()
            ->toArray();

        /**
         * select
        om_warehouse_general.a,
        om_product.cover_img,
        om_product.product_name,
        om_product.product_price_one,
        om_product.international_code
        from om_warehouse_general
        Inner join om_product on om_product.id = om_warehouse_general.product_id
        where om_warehouse_general.warehouse_id = 1 and om_warehouse_general.product_id = 2238*/
        $product = (new \app\admin\model\WarehouseGeneral())
            ->join("om_product","om_product.id = om_warehouse_general.product_id")
            ->field("om_warehouse_general.*,om_product.cover_img,om_product.product_name,om_product.product_price_one,om_product.international_code,om_product.sku_remark")
            ->where($where)
            ->find();
        $product['cover_img'] = imgUrlToAbsolute($product['cover_img']);
        $result = array(
            "list" => $list,
            "product" => $product
        );
        return writeJson(200,$result);
    }

    /**
     * 保存某商品在某仓库下的仓库信息
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function setProductHouseSkuList(Request $request){
        $post = $request->post();
        $admin = $this->admin;
        $warehouseLogService = new \app\admin\model\WarehouseLog();
        if($admin['account_type']==2){//如果是商家账号
            return writeJson(500,[],"您没有权限","500");
        }
        if(!isset($post["list"])){
            return writeJson(500,[],"商品批次传入有误","500");
        }
        if(!isset($post["product_id"])){
            return writeJson(500,[],"商品ID传入有误","500");
        }
        $where["warehouse_id"] = isset($post["warehouse_id"]) ? $post["warehouse_id"] : 1;
        $where["product_id"] = $post["product_id"];

        //计算总库存
        $total_stock = 0;
        $log = '';
        foreach ($post["list"] as $k => $v){
            $total_stock = $total_stock + $v["stock"];
            $post["list"][$k]["product_time"] = strtotime($v["product_time"]);
            $post["list"][$k]["warn_time"] = strtotime($v["warn_time"]);
            $post["list"][$k]["update_time"] = time();
            $log .= "[修改库存ID:".$v["id"]."的库存数量为".$v["stock"]."]";
        }

        $log .= "[修改商品ID号:" . $post["product_id"] ."的仓库总数量为".$total_stock."]";
        //记录日志
        $warehouseLogService->insertLog($admin["id"],$post["product_id"],$log,$post["warehouse_id"]);
        Db::startTrans();
        $res = (new WarehouseGeneralSku())->fieldUpdateAll($post["list"]);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'批次修改失败']));
        }
        $res = (new WarehouseGeneral())->fieldUpdate("stock",$total_stock,"",$where);
        if(!$res){
            Db::rollback();
            throw (new FailedException(['msg'=>'当前库存修改失败']));
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 保存
     * @param Request $request
     */
    public function setProductGeneralSkuExcel(Request $request){
        ini_set('max_execution_time','1000');
        header('Access-Control-Allow-Origin:* ');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId, token");
        $post = $request->post();
        //防探针
        if(request()->isOptions()){
            return;
        }

        $file = request()->file('file');
        if ($file) {
            $info = $file->move('./uploads/exam');
            $path = '/home/wwwroot/api/public/uploads/exam/' . $info->getSaveName();   //正式环境
//            $path = 'D:/phpStudy/PHPTutorial/WWW/oumaos/public/uploads/exam/' . $info->getSaveName();
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format
            $objPHPExcel = $objReader->load($path,$encode = 'utf-8');//$file_url即Excel文件的路径
            $drawing = new \PHPExcel_Writer_Excel2007_Drawing();
            $drawingHashTable = new \PHPExcel_HashTable();
            $drawingHashTable->addFromSource($drawing->allDrawings($objPHPExcel));
            $data = $objPHPExcel->getSheet(0)->toArray();//转换为数组格式

            try{
                $productCodeList = [];
                $newData = [];
                //重新整理数据
                foreach($data as $k=>$v){
                    if(empty($v[0])){ continue; }
                    if(empty($v[1])){ $v[1] = 0;}
                    $new["international_code"] = $v[0];
                    $new["now_num"] = $v[1];
                    array_push($newData,$new);
                    array_push($productCodeList,$new["international_code"]);
                }
                $productListWhere[] = ["international_code","in",$productCodeList];
                //将所有涉及到的商品信息查出
                $productList = (new \app\admin\model\Product())->where($productListWhere)->select()->toArray();

                //整理查询数据
                $productIdList = [];
                foreach($productList as $k=>$v){ array_push($productIdList,$v["id"]); }
                $warehouseGeneralWhere[] = ["product_id","in",$productIdList];
                $warehouseGeneralWhere[] = ["warehouse_id","eq",$post["warehouse_id"]];
                //根据查询到的商品Id 去目标库中查询已经存在的
                $warehouseGeneralList = (new \app\admin\model\WarehouseGeneral())->where($warehouseGeneralWhere)->select()->toArray();


                //商品更新信息
                $productDateList = [];
                //将id international_code nowNum 进行拼接
                foreach ($productList as $k=>$v){
                    foreach ($newData as $k1=>$v1){
                        if($v["international_code"] == $v1["international_code"]){
                            $v1["product_id"] = $v["id"];
                            $v1["uid"] = $v["uid"];
                            array_push($productDateList,$v1);
                        }
                    }
                }

                //获取到要更新的仓库商品情况
                $updateWarehouseGeneralList = [];
                foreach ($productDateList as $productKey=>$productVal){
                    $isExist = false;
                    foreach ($warehouseGeneralList as $generalKey=>$generalVal){
                        if($generalVal["product_id"] == $productVal["product_id"]){
                            $isExist = true;
                            $newGeneralVal["id"] = $generalVal["id"];
                            $newGeneralVal["product_id"] = $generalVal["product_id"];
                            $newGeneralVal["warehouse_id"] = $generalVal["warehouse_id"];
                            $newGeneralVal["uid"] = $productVal["uid"];
                            $newGeneralVal["stock"] = $productVal["now_num"];
                            $newGeneralVal["warehouse_batches"] = $generalVal["warehouse_batches"] + 1;
                            $newGeneralVal["update_time"] = time();
                            array_push($updateWarehouseGeneralList,$newGeneralVal);
                        }
                    }
                    if(!$isExist){
                        $newGeneral["uid"] = $productVal["uid"];
                        $newGeneral["product_id"] = $productVal["product_id"];
                        $newGeneral["stock"] = $productVal["now_num"];
                        $newGeneral["warehouse_batches"] = 1;
                        $newGeneral["status"] = 1;
                        $newGeneral["create_time"] = time();
                        $newGeneral["update_time"] = time();
                        $newGeneral["admin_id"] = $post["admin_id"];
                        $newGeneral["warehouse_id"] = $post["warehouse_id"];
                        array_push($updateWarehouseGeneralList,$newGeneral);
                    }
                }

                //根据数量添加新批次
                $updateWarehouseGeneralSkuList = [];
                foreach ($updateWarehouseGeneralList as $k=>$v){
                    $newGeneralSku["uid"] = $v["uid"];
                    $newGeneralSku["product_id"] = $v["product_id"];
                    $newGeneralSku["stock"] = $v["stock"];
                    $newGeneralSku["warehouse_id"] = $v["warehouse_id"];
                    $newGeneralSku["product_time"] = time();
                    $newGeneralSku["warn_stock"] = 0;
                    $newGeneralSku["warn_time"] = strtotime("+1 months");
                    $newGeneralSku["create_time"] = time();
                    $newGeneralSku["update_time"] = time();
                    array_push($updateWarehouseGeneralSkuList,$newGeneralSku);
                }

                //开始操作数据
                Db::startTrans();
                //更新仓库
                if(Count($updateWarehouseGeneralList) > 0){
                    $res = (new \app\admin\model\WarehouseGeneral())->fieldUpdateAll($updateWarehouseGeneralList);
                    if(!$res) {
                        Db::rollback();
                        throw new FailedException(['msg' => "更新库存失败"]);
                    }
                }

                //清除当前批次
                $warehouseGeneralSkuWhere[] = ["product_id","in",$productIdList];
                $warehouseGeneralSkuWhere[] = ["warehouse_id","eq",$post["warehouse_id"]];
                $res = (new \app\admin\model\WarehouseGeneralSku())->fieldUpdate("delete_time",time(),"",$warehouseGeneralSkuWhere);
                if(!$res) {
                    Db::rollback();
                    throw new FailedException(['msg' => "清空旧批次失败"]);
                }

                //更新批次
                if(Count($updateWarehouseGeneralSkuList) > 0){
                    $res = (new \app\admin\model\WarehouseGeneralSku())->fieldUpdateAll($updateWarehouseGeneralSkuList);
                    if(!$res) {
                        Db::rollback();
                        throw new FailedException(['msg' => "更新库存批次失败"]);
                    }
                }

                //结束导入数据
                Db::commit();
                return ajax_return('1','导入成功');
            }catch (Exception $exception){
                Db::rollback();
                throw new FailedException(['msg' => $exception->getMessage()]);
            }
        }
    }
}